import React, { useState, useEffect } from 'react';
import { StyleSheet, View, ScrollView, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import { Button, TextInput, ProgressBar, IconButton } from 'react-native-paper';
import { router } from 'expo-router';
import { useAuth } from '@/contexts/AuthContext';
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';

export default function AppearanceScreen() {
  const colorScheme = useColorScheme();
  const { userInfo, userToken, updateProfile } = useAuth();
  const tintColor = Colors[colorScheme ?? 'light'].tint;

  // 表单状态
  const [height, setHeight] = useState(userInfo?.height?.toString() || '170');
  const [weight, setWeight] = useState(userInfo?.weight?.toString() || '60');
  const [isLoading, setIsLoading] = useState(false);

  // 如果用户未登录，重定向到登录页面
  useEffect(() => {
    if (!userToken) {
      router.replace('/auth/login');
    }
  }, [userToken]);

  // 处理表单提交
  const handleSubmit = async () => {
    console.log(height,weight,'信息');
    
    if (!height || !weight) {

      Alert.alert('提示', '请填写您的身高和体重');
      return;
    }

    if (!userInfo || !userInfo.id || !userInfo.username) {
      Alert.alert('错误', '用户信息未加载，请重新登录');
      return;
    }

    console.log('开始提交外表信息:', { height, weight });
    console.log('当前用户信息:', userInfo);
    setIsLoading(true);
    try {
      // 更新用户外表信息
      console.log('调用updateProfile函数');
      const success = await updateProfile({
        height: parseInt(height, 10),
        weight: parseInt(weight, 10)
      }, null);

      console.log('更新外表信息结果:', success);
      if (success) {
        // 进入下一步 - 使用setTimeout确保导航在UI更新后执行
        console.log('外表信息更新成功，准备导航到生活方式页面');
        setTimeout(() => {
          console.log('导航到生活方式页面');
          router.push('/profile-setup/lifestyle' as any);
        }, 1000);
      } else {
        console.error('更新外表信息失败，未触发网络请求');
        Alert.alert('错误', '更新外表信息失败，请重试');
      }
    } catch (error) {
      console.error('Update profile error:', error);
      Alert.alert('错误', '发生未知错误，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  // 增减身高
  const incrementHeight = () => {
    const currentHeight = parseInt(height, 10);
    if (currentHeight < 220) {
      setHeight((currentHeight + 1).toString());
    }
  };

  const decrementHeight = () => {
    const currentHeight = parseInt(height, 10);
    if (currentHeight > 140) {
      setHeight((currentHeight - 1).toString());
    }
  };

  // 增减体重
  const incrementWeight = () => {
    const currentWeight = parseInt(weight, 10);
    if (currentWeight < 150) {
      setWeight((currentWeight + 1).toString());
    }
  };

  const decrementWeight = () => {
    const currentWeight = parseInt(weight, 10);
    if (currentWeight > 40) {
      setWeight((currentWeight - 1).toString());
    }
  };

  return (
    <ThemedView style={styles.container}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardAvoidingView}
      >
        <ScrollView contentContainerStyle={styles.scrollContent}>
          <View style={styles.header}>
            <ThemedText style={styles.title}>外表特征</ThemedText>
            <ThemedText style={styles.subtitle}>
              请填写您的身高体重等信息
            </ThemedText>
          </View>

          <ProgressBar 
            progress={2/6} 
            color={tintColor} 
            style={styles.progressBar} 
          />

          <View style={styles.formContainer}>
            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>身高 (cm)</ThemedText>
              <View style={styles.inputWithButtons}>
                <IconButton
                  icon="minus"
                  size={20}
                  onPress={decrementHeight}
                  style={styles.iconButton}
                  iconColor={tintColor}
                />
                <TextInput
                  value={height}
                  onChangeText={text => {
                    const value = parseInt(text, 10);
                    if (!isNaN(value) && value >= 140 && value <= 220) {
                      setHeight(text);
                    } else if (text === '') {
                      setHeight('');
                    }
                  }}
                  keyboardType="numeric"
                  mode="outlined"
                  style={styles.numericInput}
                  outlineColor="#CCCCCC"
                  activeOutlineColor={tintColor}
                  theme={{ roundness: 10 }}
                  right={<TextInput.Affix text="cm" />}
                />
                <IconButton
                  icon="plus"
                  size={20}
                  onPress={incrementHeight}
                  style={styles.iconButton}
                  iconColor={tintColor}
                />
              </View>
              <ThemedText style={styles.rangeText}>范围: 140-220 cm</ThemedText>
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>体重 (kg)</ThemedText>
              <View style={styles.inputWithButtons}>
                <IconButton
                  icon="minus"
                  size={20}
                  onPress={decrementWeight}
                  style={styles.iconButton}
                  iconColor={tintColor}
                />
                <TextInput
                  value={weight}
                  onChangeText={text => {
                    const value = parseInt(text, 10);
                    if (!isNaN(value) && value >= 40 && value <= 150) {
                      setWeight(text);
                    } else if (text === '') {
                      setWeight('');
                    }
                  }}
                  keyboardType="numeric"
                  mode="outlined"
                  style={styles.numericInput}
                  outlineColor="#CCCCCC"
                  activeOutlineColor={tintColor}
                  theme={{ roundness: 10 }}
                  right={<TextInput.Affix text="kg" />}
                />
                <IconButton
                  icon="plus"
                  size={20}
                  onPress={incrementWeight}
                  style={styles.iconButton}
                  iconColor={tintColor}
                />
              </View>
              <ThemedText style={styles.rangeText}>范围: 40-150 kg</ThemedText>
            </View>
          </View>

          <View style={styles.buttonContainer}>
            <Button
              mode="contained"
              onPress={handleSubmit}
              style={styles.button}
              labelStyle={styles.buttonText}
              loading={isLoading}
              disabled={isLoading}
              theme={{ roundness: 10 }}
              icon="arrow-right"
            >
              下一步
            </Button>

            <Button
              mode="outlined"
              onPress={() => router.push('/profile-setup/basic-info')}
              style={[styles.button, styles.backButton]}
              labelStyle={styles.backButtonText}
              theme={{ roundness: 10 }}
              icon="arrow-left"
            >
              返回
            </Button>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    padding: 20,
  },
  header: {
    marginBottom: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 16,
    opacity: 0.7,
  },
  progressBar: {
    marginBottom: 20,
    height: 8,
    borderRadius: 4,
  },
  formContainer: {
    marginBottom: 20,
  },
  formGroup: {
    marginBottom: 20,
  },
  label: {
    fontSize: 16,
    marginBottom: 8,
    fontWeight: '500',
  },
  inputWithButtons: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: 5,
  },
  numericInput: {
    flex: 1,
    backgroundColor: 'transparent',
    textAlign: 'center',
  },
  iconButton: {
    margin: 0,
  },
  rangeText: {
    fontSize: 12,
    opacity: 0.6,
    textAlign: 'right',
  },
  buttonContainer: {
    marginTop: 'auto',
    paddingTop: 20,
  },
  button: {
    marginBottom: 10,
    paddingVertical: 8,
  },
  buttonText: {
    fontSize: 16,
  },
  backButton: {
    borderColor: '#CCCCCC',
  },
  backButtonText: {
    fontSize: 16,
  },
});
